<?php
/**
 * huhaiqin,2025.2.5
 * 游戏模块用户接口
 */
namespace Game\Controller;
use Common\Controller\CommonController;

class AuthController extends CommonController{

    public function test_log(){
        $res = M('GameUser')->field('id, update_time, create_time, distance')->select();
        $result = [
            0 => 0,
            1 => 0,
            2 => 0,
            3 => 0,
            4 => 0,
            5 => 0,
            6 => 0,
            7 => 0,
            8 => 0,
            9 => 0,
            10 => 0,
        ];
        $today = 0;
        foreach($res as $k => $v){
            $v['update_date'] = date('Y-m-d', $v['update_time']);
            if($v['update_time'] > strtotime('2025-04-23 00:00:00') ){
                $today ++;
            }
            foreach($result as $k2 => $v2){

                if(($v['update_time'] - $v['create_time']) > 3600 * 24 * $k2){
                    $result[$k2]++;
                }
                if($v['create_time'] > strtotime('2025-04-14 00:00:00') + 3600 * 24 * $k2 && $v['create_time'] < strtotime('2025-04-14 00:00:00') + 3600 * 24 * ($k2 + 1)){
                    $result[date('Y-m-d', strtotime('2025-04-14 00:00:00') + 3600 * 24 * $k2 )]['create']++;
                    foreach($result as $k3 => $v3){
                        if($v['update_time']  - $v['create_time'] >= 3600 * 24 * $k3){
                            $result[date('Y-m-d', strtotime('2025-04-14 00:00:00') + 3600 * 24 * $k2 )][$k3]++;
                        } 
                    }
                }
            }
        }
        dump($result);
        dump($today);
    }
    /**
     * du 2025.2.7
     * 获取token
     */
    public function get_token() {
        if(!I('uid')){
            _apiReturn(0, '用户id不能为空');
            return;
        }
        $uid = I('uid');
        $secret_key = C('TOKEN_SECRET_KEY');
        $token = hash_hmac('sha256', $uid, $secret_key);
        _apiReturn(1, '获取成功', ['token' => $token]);
    }

    public function test(){
        dump(_get_latest_stage_id(null));
    }

    /**
     * du 2025.2.7
     * 微信登录
     * 请求参数
     * code: string //微信登录code,
     * 返回参数
     * uid: string //openid
     */
    public function wx_login(){
        if(!I('code')){
            _apiReturn(0, 'code不能为空');
            return;
        }
        $code = I('code');
        //小游戏app_id和app_secret
        $app_id = 'wx8420ab23c390fc12';
        $app_secret = '0dc7fc04dc347b66e945d34d59bc9d41';
        // 向微信后台提交auth.code2Session请求
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $app_id . '&secret=' . $app_secret . '&js_code=' . $code . '&grant_type=authorization_code';
        // 初始化curl
        $ch = curl_init();
        // 设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行curl请求
        $output = curl_exec($ch);
        // 关闭curl
        curl_close($ch);
        // 将json字符串转换为数组
        $output = json_decode($output, true);

        // 判断是否请求成功
        if($output['errcode']){
            _apiReturn(0, $output['errmsg']);
            return;
        }
        // 获取openid
        $openid = $output['openid'];
        $unionid = $output['unionid'];
        $client = 'weixin';
        $info = [
            'nickname' => I('nickName', ''),
            'avatar_url' => I('avatarUrl', ''),
            'tel' => I('phoneNumber', ''),
        ];
        //获取用户信息
        $res = D('GameUser', 'Service')->user_login($openid, $unionid, $client, $info);
        if(!$res['status']){
            _apiReturn(0, $res['msg']);
            return;
        }
        $uid = $res['data']['uid'];
        $role = $res['data']['role'];
        // 登录日志
        _write_user_log($uid, 'wx_login', $_SERVER['REMOTE_ADDR']);
        // token payload 保存uid,role,expire_time 用json编码
        $expire_time = strtotime('tomorrow midnight');
        $token_payload = json_encode(['uid' => $uid, 'role' => $role, 'expire_time' => $expire_time]);
        // 计算签名
        $sign = hash_hmac('sha256', $token_payload, C('TOKEN_SECRET_KEY'));
        // 生成token并返回
        $token = base64_encode($token_payload) . '.' . base64_encode($sign);
        _apiReturn(1, $res['msg'], ['uid' => $uid, 'expire_time' => $expire_time, 'token' => $token]);
    }

    /**
     * du 2025.2.7
     * 统一游戏登录入口
     * 请求参数
     * code: string //微信登录code,
     */
    public function game_login(){
        if(!I('openid')){
            _apiReturn(0, 'openid不能为空');
            return;
        }
        $openid = I('openid');
        $client = I('client', 'default');
        $info = [
            'nickname' => I('nickName', ''),
            'avatar_url' => I('avatarUrl', ''),
            'tel' => I('phoneNumber', ''),
        ];
        //获取用户信息
        $res = D('GameUser', 'Service')->user_login($openid, $client, $info);
        if(!$res['status']){
            _apiReturn(0, $res['msg']);
            return;
        }
        $uid = $res['data']['uid'];
        $role = $res['data']['role'];
        // 登录日志
        _write_user_log($uid, 'game_login', $_SERVER['REMOTE_ADDR']);
        // token payload 保存uid,role,expire_time 用json编码
        $expire_time = strtotime('tomorrow midnight');
        $token_payload = json_encode(['uid' => $uid, 'role' => $role, 'expire_time' => $expire_time]);
        // 计算签名
        $sign = hash_hmac('sha256', $token_payload, C('TOKEN_SECRET_KEY'));
        // 生成token并返回
        $token = base64_encode($token_payload) . '.' . base64_encode($sign);
        _apiReturn(1, $res['msg'], ['uid' => $uid, 'expire_time' => $expire_time, 'token' => $token]);
    }

    /*
     * du 2025.2.7
     * H5页面手机号登录
     * 请求参数
     * tel: string //手机号,
     * code: string //验证码,
     * 返回参数
     * token: string //token
     * 
     */
    public function web_login(){
        // 获取手机号和验证码输入
        if(!I('tel')){
            _apiReturn(0, '手机号不能为空');
            return;
        }
        if(!I('code')){
            _apiReturn(0, '验证码不能为空');
            return;
        }
        // 检查验证码
        $verify = true;
        if(!$verify){
            _apiReturn(0, '验证码无效');
            return;
        }
        // 获取用户信息
        $user_info = D('GameUser')->where(['tel'=>I('tel'), 'client' => 'web'])->find();
        if(!$user_info){
            //用户不存在，创建用户
            $post = [
                'tel' => I('tel'),
                'client' => 'web'
            ];
            D('GameUser')->_add_game_user($post); 
        }
        // 获取uid
        _apiReturn(1, '登录成功', ['uid' => I('tel')]);
    }
}